/**
 * Created by Lxp on 16/4/5.
 */
require.config(require_config);

define([
    'jquery',
    'common',
    'ready',
    'collection',
    'template',
    'model',
    'dialog',
    'datepicker'
], function ($, common, ready, Collection, template, Model, dialog, datepicker) {
    var index = function () {
        this.init();
    };
    index.prototype = {
        init: function () {
            loading();
            this.fetch();
            this.event();
        },

        fetch: function () {
            var _this = this;
            this.collection = new Collection({
                url: _global.url.api + 'cards',
                condition: {},
                model: {
                    url: _global.url.api + 'card',
                    event: {
                        '.edit_listorder:change': 'setlistorder',
                        '.item-del:click': 'delcard',
                        '.item-edit:click': 'edit',
                        '.item-zone:click': 'zone'
                    },
                    setlistorder: function (e) {
                        e.preventDefault();
                        var id = this.data.id;
                        var listorder = $('input[name="edit_listorder_' + id + '"]').val();
                        if (new Model({
                                url: _global.url.api + 'card',
                                data: {id: id, listorder: listorder, act: 'listorder'}
                            }).put()) {
                            _this.collection.fetch();
                        }
                    },
                    delcard: function (e) {
                        e.preventDefault();
                        var id = this.data.id;
                        dialog({
                            content: '确定要删除它？',
                            ok: function () {
                                if (new Model({
                                        url: _global.url.api + 'card',
                                        data: {id: id}
                                    }).delete()) {
                                    _this.collection.fetch();
                                }
                            }, cancel: function () {
                            }
                        }).show(e.target);
                    },
                    edit: function (e) {
                        e.preventDefault();
                        var id = this.data.id;
                        var type = this.data.type + '';
                        var title = this.data.type_name;

                        this.data.type = type;
                        this.data.act = 'edit';
                        var __this = this;

                        var html = template("add-tpl-" + type, this.data);
                        dialog({
                            'title': '编辑:' + title,
                            'content': html,
                            'width': 700,
                            ok: function () {
                                return _this.check_data(__this);
                            }, cancel: function () {
                            }
                        }).show();
                    },
                    zone: function (e) {
                        e.preventDefault();
                        var id = this.data.id;
                        dialog({
                            title: '投放',
                            content: template('zone-tpl', this.data),
                            width: 500,
                            ok: function () {
                                var zone = $('input[name="zone"]:checked').val();
                                var started_at = $('input[name="started_at"]').val();
                                var expired_at = $('input[name="expired_at"]').val();
                                var listorder = $('input[name="listorder"]').val();
                                if (zone == '') {
                                    Alert({msg: '请选择投放区域', type: 'error'});
                                    return false;
                                }
                                if (started_at == '') {
                                    Alert({msg: '请选择时间', type: 'error'});
                                    return false;
                                }
                                if (expired_at == '') {
                                    Alert({msg: '请选择时间', type: 'error'});
                                    return false;
                                }
                                if (new Model({
                                        url: _global.url.api + 'card',
                                        data: {
                                            id: id,
                                            act: 'zone',
                                            zone: zone,
                                            listorder: listorder,
                                            started_at: started_at,
                                            expired_at: expired_at
                                        }
                                    }).put()) {
                                    _this.collection.fetch();
                                    return true;
                                }
                                return false;
                            }, cancel: function () {
                            }
                        }).show();
                    }
                },
                callback: function () {
                    loaded();
                    if ($('[name="cate"]').children().size() == 1) {
                        $.each(_this.collection.result._card_cate_list, function (n, v) {
                            $('[name="cate"]').append('<option value="' + v.id + '">' + v.name + '</option>');
                        });
                    }
                }
            });
            this.collection.fetch();
        },

        check_data: function (__this) {
            var _this = this;
            var data = __this.data;
            if (data.type < 1) {
                Alert({msg: '请选择添加的类型', type: 'error'});
                return false;
            }
            data.title = $('[name=title]').val();
            if (data.title == '') {
                Alert({msg: '请输入标题', type: 'error'});
                return false;
            }
            data.intro = $('[name=intro]').val();
            if (data.intro == '') {
                Alert({msg: '请输入备注', type: 'error'});
                return false;
            }
            data.corner_ico = $.trim($('[name="corner_ico"]:checked').val());
            data.tag_limit = $('[name="tag_limit"]:checked').val();
            var user_tag_id_arr = new Array();
            $('[name="user_tag_id"]:checked').each(function (i) {
                var user_tag_id = $.trim($(this).val());
                user_tag_id_arr.push(user_tag_id);
            });
            var card_cate = new Array();
            $('[name="card_cate"]:checked').each(function (i) {
                var card_cate_id = $.trim($(this).val());
                card_cate.push(card_cate_id);
            });
            if (data.tag_limit == 1) {
                if (user_tag_id_arr.length < 1) {
                    Alert({msg: '请选择用户标签', type: 'error'});
                    return false;
                }
            }
            data.user_tag_id = user_tag_id_arr;
            data.card_cate = card_cate;

            data.url = $('[name=url]').val();
            data.content = $.trim($('[name=content]').val());
            data.image = $.trim($('[name=image]').val());
            var msg = '';

            switch (data.type) {
                case '1' :
                    //单图
                    data.width = $.trim($('[name=width]').val());
                    data.height = $.trim($('[name=height]').val());
                    if (data.width == '') {
                        msg = '请输入宽度';
                        break;
                    }
                    if (data.height == '') {
                        msg = '请输入高度';
                        break;
                    }
                    if (data.image == '') {
                        msg = '请上传图片';
                        break;
                    }
                    break;
                case '2':
                    //分享家
                    data.name = $.trim($('[name=name]').val());
                    data.profession = $.trim($('[name=profession]').val());
                    data.city = $.trim($('[name=city]').val());
                    data.sign = $.trim($('[name=sign]').val());
                    data.join_time = $.trim($('[name=join_time]').val());
                    data.income = $.trim($('[name=income]').val());
                    data.friend_count = $.trim($('[name=friend_count]').val());
                    data.share_count = $.trim($('[name=share_count]').val());
                    if (data.nickname == '') {
                        msg = '请输入昵称';
                        break;
                    }
                    if (data.profession == '') {
                        msg = '请输入职业';
                        break;
                    }
                    if (data.city == '') {
                        msg = '请输入城市';
                        break;
                    }
                    if (data.join_time == '') {
                        msg = '请输入加入时间';
                        break;
                    }
                    if (data.sign == '') {
                        msg = '请输入签名';
                        break;
                    }
                    if (data.friend_count == '') {
                        msg = '请输入小伙伴预置数';
                        break;
                    }
                    if (data.income == '') {
                        msg = '请输入收入预置数';
                        break;
                    }
                    if (data.share_count == '') {
                        msg = '请输入分享预置数';
                        break;
                    }
                    if (data.image == '') {
                        msg = '请上传头像';
                        break;
                    }
                    break;
                case '3':
                case '11':
                case '12':
                    //特卖
                    data.goods_id = $.trim($('[name=goods_id]').val());
                    data.share_count = $.trim($('[name=share_count]').val());
                    data.goods_lock = $.trim($('[name=goods_lock]:checked').val());
                    data.lock_started_at = $.trim($('[name=lock_started_at]').val());
                    data.lock_expired_at = $.trim($('[name=lock_expired_at]').val());
                    data.width = $.trim($('[name=width]').val());
                    data.height = $.trim($('[name=height]').val());

                    var date1 = new Date(Date.parse(data.started_at));
                    var date2 = new Date(Date.parse(data.expired_at));
                    if (data.goods_lock == 1) {
                        if (data.started_at == '' || data.expired_at == '') {
                            Alert({msg: '请选择锁定时间！', type: 'error'});
                            return false;
                        }
                    }
                    if (date1.getTime() > date2.getTime()) {
                        Alert({msg: '开始时间不能大于结束时间', type: 'error'});
                        return false;
                    }
                    if (data.width == '') {
                        msg = '请输入宽度';
                        break;
                    }
                    if (data.height == '') {
                        msg = '请输入高度';
                        break;
                    }
                    /*if (data.content == '') {
                     msg = '请输入描述';
                     break;
                     }*/
                    if (data.goods_id == '') {
                        msg = '请输入商品ID';
                        break;
                    }
                    if (data.image == '') {
                        msg = '请上传图片';
                        break;
                    }
                    break;
                case '4':
                    //拼团
                    data.goods_id = $.trim($('[name=goods_id]').val());
                    data.share_count = $.trim($('[name=share_count]').val());
                    data.width = $.trim($('[name=width]').val());
                    data.height = $.trim($('[name=height]').val());
                    data.goods_lock = $.trim($('[name=goods_lock]:checked').val());
                    data.started_at = $.trim($('[name=started_at]').val());
                    data.expired_at = $.trim($('[name=expired_at]').val());

                    var date1 = new Date(Date.parse(data.started_at));
                    var date2 = new Date(Date.parse(data.expired_at));
                    if (data.goods_lock == 1) {
                        if (data.started_at == '' || data.expired_at == '') {
                            Alert({msg: '请选择锁定时间！', type: 'error'});
                            return false;
                        }
                    }

                    if (data.width == '') {
                        msg = '请输入宽度';
                        break;
                    }
                    if (data.height == '') {
                        msg = '请输入高度';
                        break;
                    }
                    /*if (data.content == '') {
                     msg = '请输入描述';
                     break;
                     }*/
                    if (data.goods_id == '') {
                        msg = '请输入商品ID';
                        break;
                    }
                    if (data.image == '') {
                        msg = '请上传图片';
                        break;
                    }
                    break;
                case '5':
                    //笔记
                    data.layout = $.trim($('[name=layout]:checked').val());
                    data.cover_text = $.trim($('[name=cover_text]').val());
                    data.tag_text = $.trim($('[name=tag_text]').val());
                    data.width = $.trim($('[name=width]').val());
                    data.height = $.trim($('[name=height]').val());
                    data.video = $('[name="video"]:checked').val();
                    if (data.video == 1) {
                        if (data.layout == '') {
                            msg = '请选择布局';
                            break;
                        }
                    } else {

                        if (data.width == '') {
                            msg = '请输入宽度';
                            break;
                        }
                        if (data.height == '') {
                            msg = '请输入高度';
                            break;
                        }
                        if (data.image == '') {
                            msg = '请上传图片';
                            break;
                        }

                    }


                    /*if (data.layout != 0 && data.cover_text == '') {
                     msg = '请输入文案';
                     break;
                     }
                     if (data.tag_text == '') {
                     msg = '请输入系列名字';
                     break;
                     }*/
                    /*if (data.content == '') {
                     msg = '请输入内容';
                     break;
                     }*/

                    break;
                case '6' :
                    //填充
                    data.width = $.trim($('[name=width]').val());
                    data.height = $.trim($('[name=height]').val());
                    data.started_at = $.trim($('[name=started_at]').val());
                    data.expired_at = $.trim($('[name=expired_at]').val());
                    if (data.width == '') {
                        msg = '请输入宽度';
                        break;
                    }
                    if (data.height == '') {
                        msg = '请输入高度';
                        break;
                    }
                    if (data.image == '') {
                        msg = '请上传图片';
                        break;
                    }
                    break;
                case '100' :
                    //卡片组
                    data.cards = $.trim($('[name=cards]').val());
                    if (data.cards == '') {
                        msg = '请输入卡片ID';
                        break;
                    }
                    break;
                default :
                    msg = '请填写所有信息';
                    alert(msg);
                    break;

            }
            if (msg != '') {
                Alert({msg: msg, type: 'error'});
                return false;
            }
            if (data.id) {
                if (new Model({
                        url: _global.url.api + 'card',
                        data: data
                    }).put()) {
                    _this.collection.reload();
                    return true;
                }
            } else {
                if (new Model({
                        url: _global.url.api + 'card',
                        data: data
                    }).post()) {
                    _this.collection.reload();
                    return true;
                }
            }
            return false;
        },

        event: function () {
            this.data = {};
            var _this = this;
            //日期
            $('body').on('click', '.long_date', function (e) {
                WdatePicker({
                    el: this.id,
                    dateFmt: 'yyyy-MM-dd HH:mm:ss'
                });
            });
            $('body').on('click', '.date', function (e) {
                WdatePicker({
                    el: this.id,
                    dateFmt: 'yyyy.MM.dd'
                });
            });
            $('body').on('click', '[name="video"]', function (e) {
                var video = $('[name="video"]:checked').val();
                if (video == 1) {
                    $('#image-upload').hide();
                } else {
                    $('#image-upload').show();
                }
            });

            $('body').on('click', '[name="tag_limit"]', function (e) {
                var tag_limit = $('[name="tag_limit"]:checked').val();
                if (tag_limit == 1) {
                    $('.card_user_tag').show();
                } else {
                    $('.card_user_tag').hide();
                }
            });

            $('.btn-group a').on('click', function () {
                var rel = $(this).attr('rel');
                if (rel == 'from_sale') {
                    $('#from_exist').show();
                } else {
                    $('#from_exist').hide();
                }
            });

            $("#btn-clare").on("click", function (e) {
                e.preventDefault();
                dialog({
                    'title': '清所有卡片缓存',
                    'content': '已经测试了吗？确定清除吗',
                    ok: function () {
                        if (new Model({
                                url: _global.url.api + 'clear_rediskey'
                            }).put()) {
                        }
                        ;
                    }, cancel: function () {
                    }
                }).show(e.target);
            });


            $("#btn-test-config").on("click", function (e) {
                e.preventDefault();
                $.ajax({
                    url: _global.url.api + 'homepage_test_config',
                    data: {act: 'get'},
                    type: 'post',
                    async: false,
                    success: function (res) {
                        if (res.code == 0) {
                            dialog({
                                'title': '测试首页预发布设置',
                                width: 800,
                                'content': template("test-config-tpl", res.data),
                                ok: function () {
                                    var data = {};
                                    data.act = 'set';
                                    data.is_open = $('input[name=is_open]:checked').val();
                                    data.user_tag_ids = $('input[name=user_tag_ids]').val();
                                    if (new Model({
                                            url: _global.url.api + 'homepage_test_config',
                                            data: data
                                        }).post()) {
                                        return true;
                                    }
                                    return false;
                                }, cancel: function () {
                                }
                            }).show();
                        }
                    }
                });
            });

            /**
             * 搜索事件
             */
            $('#btn-search').on('click', function (e) {
                e.preventDefault();
                _this.collection.condition.keyword = $('input[name="keyword"]').val();
                _this.collection.condition.zone = $('[name="zone"]').val();
                _this.collection.condition.cate = $('[name="cate"]').val();
                _this.collection.condition.zone_type = $('[name="zone_type"]').val();
                _this.collection.condition.from_sale = $('[name="from_sale"]').val();
                _this.collection.condition.zone_start_time = $('[name="zone_start_time"]').val();
                _this.collection.condition.zone_end_time = $('[name="zone_end_time"]').val();
                _this.collection.condition.from_sale_start_time = $('.from_sale_start_time').val();
                _this.collection.condition.from_sale_end_time = $('.from_sale_end_time').val();
                _this.collection.reload();
            });

            /**
             * 按状态查询
             */
            $('#btn-status').find('a').on('click', function (e) {
                e.preventDefault();
                $('input[name="keyword"]').val('');
                $('[name="zone"]').val('all');
                $('[name="cate"]').val('all');
                $('[name="zone_start_time"]').val('');
                $('[name="zone_end_time"]').val('');
                _this.collection.condition.keyword = '';
                _this.collection.condition.zone = '';
                _this.collection.condition.cate = '';
                _this.collection.condition.zone_start_time = '';
                _this.collection.condition.zone_end_time = '';
                _this.collection.condition.from_sale = '';
                _this.collection.condition.from_sale_start_time = '';
                _this.collection.condition.from_sale_end_time = '';
                _this.collection.condition.type = $(e.target).attr('rel');
                _this.collection.reload();
                $(e.target).addClass('active').siblings().removeClass('active');
            });
            //保存
            $(".btn-add").on("click", function (e) {
                e.preventDefault();
                var type = $(this).attr('data-type');
                var title = $(this).text();
                var html = template("add-tpl-" + type, {
                    config: {},
                    card_user_tag: _this.collection.result._user_tag_list,
                    card_cate_list: _this.collection.result._card_cate_list
                });
                dialog({
                    'title': '添加:' + title,
                    'content': html,
                    'width': 700,
                    ok: function () {
                        _this.data.type = type;
                        return _this.check_data(_this);
                    }, cancel: function () {
                    }
                }).show();
            });

            //上传图片
            $('body').on('click', '#btn-upload', function (e) {
                _this.upload_dialog = dialog({
                    content: template('upload-tpl', {}),
                    width: 550,
                    ok: function () {
                        var img = $("#upload-frame")[0].contentWindow.image.get();
                        _this.imgPreview(img);
                    }, cancel: function () {
                    }
                });
                _this.upload_dialog.show();
            });
        },
        imgPreview: function (img) {
            if (typeof img.id !== 'undefined') {
                $('#img-view').html(template('img-tpl', img));
            }
        },

        change: function (e) {
            this.data[$(e.target).attr('name')] = $(e.target).val();
        }
    };

    new index();

});